/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.backendbean;

import org.apache.http.HttpResponse;
import org.retabel.jsf.DocumentConfigurationUriBuilder;
import org.retabel.jsf.PagedListDataModel;
import org.retabel.ui.DocumentConfigurationUI;
import org.retabel.util.HttpDeleteClientRequestRunner;
import org.retabel.util.HttpGetClientRequestRunner;
import org.retabel.util.JaxbUtils;
import org.retabel.util.LogLines;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xsd.documentconfigurations.DocumentConfiguration;
import xsd.documentconfigurations.DocumentConfigurations;

import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;

@ManagedBean
@RequestScoped
@Named
public class DocumentConfigurationListBean extends PagedListBean {

    // constants

    private static final Logger log = LoggerFactory.getLogger(DocumentConfigurationListBean.class);

    // private fields

    private LogLines logLines = new LogLines(log);

    // private functions

    private DocumentConfigurations getPage(int first, int maxRows) throws Exception {
        // we don't want any log lines, use null as log lines parameter therefore
        return new HttpGetClientRequestRunner<DocumentConfigurations>(null) {
            @Override
            protected DocumentConfigurations onSuccess(HttpResponse response, LogLines logLines) throws Exception {
                return JaxbUtils.unmarshal(DocumentConfigurationUriBuilder.getDocumentConfigurationsXmlSchemaURI().toURL(),
                                           response.getEntity().getContent(), DocumentConfigurations.class);
            }

            @Override
            protected void onFailure(HttpResponse response, LogLines logLines) throws Exception {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                                    "request failed",
                                                                                    response.getStatusLine().toString()));
            }
        }.run(DocumentConfigurationUriBuilder.getDocumentConfigurationsURI(first, maxRows));
    }

    // protected methods

    @Override
    protected DataModel getDataModel() throws Exception {
        DocumentConfigurations documentConfigurations = getPage(getUiData().getFirst(), getUiData().getRows());

        List<DocumentConfigurationUI> documentConfigurationUIs = new ArrayList<>();
        int count = 0;

        if (documentConfigurations != null && documentConfigurations.getList() != null) {
            count = documentConfigurations.getCount();

            for (DocumentConfiguration documentConfiguration : documentConfigurations.getList().getDocumentConfiguration()) {
                DocumentConfigurationUI documentConfigurationUI = new DocumentConfigurationUI();

                documentConfigurationUI.setName(documentConfiguration.getName());
                documentConfigurationUI.setVersion(documentConfiguration.getVersion());
                documentConfigurationUI.setUri(DocumentConfigurationUriBuilder.getDocumentConfigurationURI(
                    documentConfiguration.getName(), documentConfiguration.getVersion()));

                documentConfigurationUIs.add(documentConfigurationUI);
            }
        }

        return new PagedListDataModel(documentConfigurationUIs, count, getUiData().getRows());
    }

    // public functions

    @Override
    public void delete() throws Exception {
        DocumentConfigurationUI documentConfigurationUI = (DocumentConfigurationUI) getUiData().getRowData();

        new HttpDeleteClientRequestRunner<Boolean>(logLines) {
            @Override
            protected Boolean onSuccess(HttpResponse response, LogLines logLines) throws Exception {
                logLines.log(getResponseContentAsString(response));

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
                                                                                    "document configuration deleted "
                                                                                    + "successfully",
                                                                                    response.getStatusLine().toString()));

                return Boolean.TRUE;
            }

            @Override
            protected void onFailure(HttpResponse response, LogLines logLines) throws Exception {
                logLines.log(getResponseContentAsString(response));

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                                    "delete document configuration failed",
                                                                                    response.getStatusLine().toString()));
            }
        }.run(DocumentConfigurationUriBuilder.getDocumentConfigurationDeleteURI(documentConfigurationUI.getName(),
                                                                                documentConfigurationUI.getVersion()));
    }

}